package com.papper.mng.controller.system;

import com.papper.common.bean.sys.SysUser;
import com.papper.common.service.sys.SysUserService;
import com.papper.common.utils.encrypt.Md5Tool;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author:Lajiao
 * @Date:2014年8月21日
 * @Time:下午12:42:13
 * @Description:密码修改
 */
@Controller
public class PasswordController extends BaseAction {

    @Autowired
    SysUserService sysUserService;

    @GetMapping(value = "/password/change")
    public String passwordChangeGet(Model model) {
        return render("system/password/change");
    }

    @PostMapping(value = "/password/change")
    @ResponseBody
    public DwzResponse passwordChangePost(HttpServletResponse _response, String oldPass, String newPass, String confimPass) {
        SysUser sysUser = getLoginUser();
        try {
            if (sysUser.getId().intValue() == 0) {
                return new DwzResponse("300", "超级管理员不能修改密码！");
            }

            if (StringUtil.isEmpty(oldPass) || StringUtil.isEmpty(newPass)) {
                return new DwzResponse("300", "参数为空异常！");
            }

            if (newPass.equals(oldPass)) {
                return new DwzResponse("300", "新旧密码输入一致！");
            }

            SysUser oldUser = sysUserService.findById(sysUser.getId());
            if (oldUser == null) {
                return new DwzResponse("300", "您没有权限修改该用户！");
            }

            if (!Md5Tool.getMd5(oldPass).equals(oldUser.getLoginPass())) {
                return new DwzResponse("300", "密码不正确！");
            }

            sysUserService.updatePassword(sysUser.getId(), Md5Tool.getMd5(newPass));
            return new DwzResponse("200", "密码修改成功！", "closeCurrent");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new DwzResponse("300", "系统错误[" + ex.getMessage() + "],请稍候再试！");
        }
    }
}
